from myelin.Ns import MYELINS, MYELIN
from myelin.server.core.ft import ModelDriver
from nodetypes.formats.mml.Events import Form

from nodetypes.Ns import GRAPHS_NS
from nodetypes import config
from nodetypes.lib import Utils
from nodetypes.models.TextIndex import TextIndexDocument


class Form(Form):
    
    defaults = config.METASEARCH_PARAMS
    newTextIndexDocument        = TextIndexDocument.Retrieve
    newTextIndexDriver          = TextIndexDocument.Initialize
    
    #formClass = u'search'
    defaultSubmitAction = u'query'
    
    def createInstance(self, context, node):
        defaults = context.defaults
        map = context.uriMapper.apply
        
        eventData = context.event.data
        config = eventData.config
        print "CONFIG PARAMS: ", config.params
        
        model = context.model
        
        nxa = node.xml_append
        nxc = node.xml_create_element
        
        paramDefaults = self.defaults
        
        self.createMethodOptions(
            context,
            nxa(
                nxc(
                    u'a:method', MYELINS
                )            
            ),
            (context.nodeType.actions.get(self.defaultSubmitAction) or {}).keys()
        ) 
        
        nxa(
            nxc(
                u'a:query', MYELINS
            )
        )
        
        value = Utils.SplitLocale(model.rdf_join('dcLanguage'))
        nxa(
            nxc(
                u'a:language', MYELINS,
                attributes = {
                    u'selected' : value[0],
                }
            )
        )
        
        #nxa(
        #    nxc(
        #        u'a:region', MYELINS,
        #        attributes = {
        #            u'selected' : value[1],
        #        }
        #    )
        #)        
        
        #value = context.session.dateTime
        #dsy = unicode(
        #    getattr(
        #        defaults,
        #        'default_search_start_year',
        #        paramDefaults['search-start-year']
        #    )
        #)
        #nxa(
        #    nxc(
        #        u'a:effectiveDate', MYELINS,
        #        attributes = {
        #            u'year' : dsy,
        #            u'mon'  : u'1',
        #            u'start-year' : dsy,
        #            u'end-year' : unicode(value.year),
        #        }
        #    )
        #)        
        
        self.createTextIndexUriOptions(
            context,
            nxa(
                nxc(
                    u'a:textindex-uri', MYELINS,
                )
            )
        )
        
        
        # count select
        nxa(
            nxc(
                u'a:count', MYELINS,
                attributes = {
                    u'min'      : config.params.get((None,'default-count-min')) or paramDefaults['search-count-min'],
                    u'max'      : config.params.get((None,'default-count-max')) or paramDefaults['search-count-max'],
                    u'step'     : config.params.get((None,'default-count-step')) or paramDefaults['search-count-step'],
                    u'selected' : config.params.get((None,'default-count')) or paramDefaults['search-count'],
                }
            )
        )
        
        nxa(
            nxc(
                u'a:page', MYELINS,
                content = u'0'
            )
        )
        
        #nxa(
        #    nxc(
        #        u'a:sort-by', MYELINS,
        #        attributes = {
        #            u'selected'     : u'0',
        #        }
        #    )
        #)
        #
        #nxa(
        #    nxc(
        #        u'a:sort-direction', MYELINS,
        #        attributes = {
        #            u'selected'     : u'0',
        #        }
        #    )
        #)
        
        #nxa(
        #    nxc(
        #        u'a:publish-type', MYELINS,
        #        attributes = {
        #            u'selected' : u'0',
        #        }
        #    )
        #)
        
        # publishPeriod
        
        # type
        
        return node
    
    def createTextIndexUriOptions(self, context, node, selected=None):
        repo = context.repo
        eventData = context.event.data
        
        newTextIndexDoc = self.newTextIndexDocument
        newTextIndexDriver = self.newTextIndexDriver
        
        locale = context.preferences['locale']
        acls = context.acls.checkNodeAcls
        umap = context.uriMapper.apply
        
        nxa = node.xml_append
        nxc = node.xml_create_element
        
        config = eventData.config
        defaultTextIndices = config.defaultTextIndices
        
        if selected is None:
            selected = defaultTextIndices
        
        for k,g in config.textIndices.iteritems():            
            if __debug__: print "RESET TI: ", (k,g.descUri)
            if not g.descUri:
                if k in selected:
                    atts = {
                        u'key'  : unicode(k),
                        u'selected' : u'1',
                    }
                else:
                    atts = {
                        u'key'  : unicode(k),
                    }
                    
                nxa(
                    nxc(
                        u'a:option', MYELINS,
                        attributes = atts,
                        content = unicode(k)
                    )
                )
                continue
            g = repo.fetchResourceByUri(g.descUri)
            s = g.getAbsolutePathAsUri()
            m = newTextIndexDoc(
                newTextIndexDriver(g.getModel().driver),
                g.uri,
                s, s
            )
                
            if locale not in m.dcLanguage:
                for t in m.mTranslation:
                    if locale in t.dcLanguage:
                        m = t
                        break
            alt = m.rdf_join('dcAlternative')
            if alt:
                title = m.rdf_join('dcTitle')
                if title:
                    if len(alt) < len(title):
                        title = alt
                else:
                    title = alt
            else:
                title = m.rdf_join('dcTitle')
                
            if acls(m.rdf_domain,'view'):
                atts = {
                    u'key'  : unicode(k),
                    u'uri'  : umap(m.rdf_domain),
                }
                if k in defaultTextIndices:
                    atts[u'default'] = u'1'
                if k in selected:
                    atts[u'selected'] = u'1'                    
               
                nxa(
                    nxc(
                        u'a:option', MYELINS,
                        attributes = atts,
                        content = title or unicode(k)
                    )
                )
        
        #server = context.server
        #
        #driver = server.graphs.get(GRAPHS_NS + 'site')
        #if driver:
        #    #print "SITE GRAPHS: ", driver
        #    driver = self.newModelDriver(
        #        context.repo,
        #        reduce(lambda a,b:a+b,driver.values(),[])
        #    )
        #else:
        #    driver = context.dbDriver
        #
        #locale = context.preferences.get('locale') or \
        #    getattr(context.defaults,'default_locale')
        #acls = context.acls.checkNodeAcls
        #umap = context.uriMapper.apply
        #
        #graphs = {}
        #pred = MYELIN + u'for-graph'
        #
        #newGraph = self.newGraphDocument
        #
        #nxa = node.xml_append
        #nxc = node.xml_create_element
        #
        #if not searchGraphs:
        #    searchGraphs = server.defaultSearchGraphs
        #defaultGraphs = server.defaultSearchGraphs
        #for uri, modelList in server.searchGraphs.items():
        #    if not modelList.descUri:
        #        # NOTICE: this updates the global server config (ie. caches the value)
        #        for m in driver.complete(None,pred,uri,None,None):
        #            modelList.descScope = m[4].split('#')[0]
        #            modelList.descUri = m[0]
        #            break
        #        else:
        #            continue
        #    
        #    m = newGraph(
        #        driver,
        #        modelList.descUri,
        #        modelList.descScope,
        #        modelList.descScope
        #    )
        #    
        #    if locale not in m.dcLanguage:
        #        for t in m.mTranslation:
        #            if locale in t.dcLanguage:
        #                m = t
        #                break
        #    alt = m.rdf_join('dcAlternative')
        #    if alt:
        #        title = m.rdf_join('dcTitle')
        #        if title:
        #            if len(alt) < len(title):
        #                title = alt
        #        else:
        #            title = alt
        #    else:
        #        title = m.rdf_join('dcTitle')            
        #        
        #    if uri in searchGraphs:
        #        n = nxa(
        #            nxc(
        #                u'a:option', MYELINS,
        #                attributes = {
        #                    u'key'  : unicode(uri),
        #                    u'uri'  : umap(m.rdf_domain),
        #                    u'selected' : u'1',
        #                },
        #                content = title or unicode(uri)
        #            )
        #        )
        #    else:
        #        n = nxa(
        #            nxc(
        #                u'a:option', MYELINS,
        #                attributes = {
        #                    u'key'  : unicode(uri),
        #                    u'uri'  : umap(m.rdf_domain),
        #                },
        #                content = title or unicode(uri)
        #            )
        #        )
        #        
        #    if uri in defaultGraphs:
        #        n.default = u'1'

# cleanup
del config